package com.gdcnano.nanoamp.media.sound
{
	import flash.media.ID3Info;
	import flash.utils.ByteArray;

	public class ID3InfoWrapper
	{
		
		private static const WIN_1251:String = "windows-1251";
		
		private static const ARTIST_SONG_DELIMITER:String = " — ";
			
		private static const L_BRACKET:String = " [";
		
		private static const R_BRACKET:String = "]";
		
		[Bindable]
		public var artist:String;
		
		[Bindable]
		public var album:String;
		
		[Bindable]
		public var songName:String;
		
		[Bindable]
		public var title:String;
		
		public function ID3InfoWrapper(id3Info:ID3Info)
		{
			if (isInWin1251Encoding(id3Info))
			{
				artist = convert(id3Info.artist);
				
				album = convert(id3Info.album);
				
				songName = convert(id3Info.songName);
			}
			else
			{
				artist = id3Info.artist;
				
				album = id3Info.album;
				
				songName = id3Info.songName;
			}
			
			title = setTitle();
		}
		
		
		private function setTitle():String
		{
			return artist + ARTIST_SONG_DELIMITER + songName + L_BRACKET + album + R_BRACKET;
		}
		
		private function convert(data:String):String
		{
			var b:ByteArray = new ByteArray();
			var charCode:Number;
			for (var i:uint = 0; i < data.length; i++)
			{
				charCode = data.charCodeAt(i);
				b[i] = charCode;
			}	
			return b.readMultiByte(b.bytesAvailable, WIN_1251);
		}
		
		private function isInWin1251Encoding(id3Info:ID3Info):Boolean
		{
			if (id3Info.artist.length > 0)
			{
				return isInWin1251Range(id3Info.artist.charCodeAt(0));
			}
			else if(id3Info.songName.length > 0)
			{
				return isInWin1251Range(id3Info.album.charCodeAt(0));
			}
			
			return false;
		}
		
		private function isInWin1251Range(charCode:Number):Boolean
		{
			return (charCode >= 192 && charCode <= 255);
		}
	}
}